package com.apes.scm.pur.purchaseOrder.model;

import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.plugin.soe.metadata.BusinessAttributeValue;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.account.account.repository.CooperationRepository;
import com.apes.scm.contract.model.Contract;
import com.apes.scm.masterdata.area.model.Area;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.model.SupplierShipItem;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.account.account.model.Cooperation;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.*;

/**
 * 功能：采购订单
 *
 * @author xul
 * @create 2018-01-25 15:44
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = PurchaseOrder.CONST_TABLE_NAME)
public class PurchaseOrder extends Model {
    public static final String CONST_TABLE_NAME = "pur_purchase_order";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "采购订单", prefix = "CG%(company)%(yy)%(month)", padding = 5, useDateRange=true)
    @Comment("采购订单号")
    private String id;


    @Column(name = "product_require_id", length = 32)
    @Comment("要货单号")
    private String productRequire;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    @Comment("公司编码")
    private PartyRole company;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    @Comment("部门编码")
    private Dept dept;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "clerk_id", referencedColumnName = "id", updatable = false)
    @Comment("业务员编码")
    private PartyRole clerk;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "contract_id", referencedColumnName = "id")
    @Comment("合同编码")
    private Contract contract;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "supplier_id", referencedColumnName = "id", nullable = false)
    @Comment("供应商编码")
    private PartyRole supplier;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "move_type", referencedColumnName = "id")
    @Comment("交货方式：（direct：部分交货，one：一次性交货）")
    private Enumeration moveType;

    @States(name = "提货方式", values = {
            @State(id = "selfMention", name = "自提"),
            @State(id = "delivery", name = "送货")
    })
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "carry_type", referencedColumnName = "id")
    private BusinessAttributeValue carryType;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "location_id", referencedColumnName = "id")
    @Comment("仓库编码")
    private Location location;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "receipt_location_id", referencedColumnName = "id")
    @Comment("对方仓库")
    private Location receiptLocation;

    @Column(name = "amt_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("税金")
    private double amtTax = 0;

    @Column(name = "amt_without_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("不含税金额")
    private double amtWithoutTax = 0;

    @Column(name = "amt_total", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("合计")
    private double amtTotal = 0;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dest_address_id", referencedColumnName = "id")
    @Comment("送达方")
    private PartyRole destAddress;

    @Column(name = "supplier_ref", length = 30)
    @Comment("第三方单号")
    private String supplierRef;

    @Column(name = "supplier_type", length = 30)
    @Comment("第三方单号类型")
    private String supplierType;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cooperation_id", referencedColumnName = "id")
    @Comment("合作方式编码")
    private Cooperation cooperation;

    @Column (name ="note")
    @Comment("备注")
    private String note;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审批人")
    private PartyRole approveUid;

    @Column(name = "date_approve")
    @Comment("审核日期")
    private Date dateApprove;

    @Column(name = "date_order")
    @Comment("单据日期")
    private Date dateOrder;

    @Column(name = "date_planned")
    @Comment("计划日期")
    private Date datePlanned;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cancel_name_id", referencedColumnName = "id")
    @Comment("终止人")
    private PartyRole cancelNameId;

    @Column(name = "date_cancel")
    @Comment("取消日期")
    private Date dateCancel;

    @States(name = "开票状态", values = {
            @State(id = "no", name = "未开票"),
            @State(id = "to_invoice", name = "开票中"),
            @State(id = "invoiced", name = "已开票")})
    @Column(name = "invoice_status", length = 10)
    private String invoiceStatus = "no";

    @Column(name = "is_shipped")
    @Comment("是否收货")
    private boolean shipped = false;

    @States(name = "订单状态", values = {
            @State(id = "sent", name = "创建"),
            @State(id = "confirmed", name = "待入库"),
            @State(id = "done", name = "已完成"),
            @State(id = "cancel", name = "已终止"),
            @State(id = "activation", name = "激活"),
            @State(id = "delay", name = "延期"),
            @State(id="delete", name="删除")}
    )
    @Column(name = "state", length = 10, nullable = false)
    private String state;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "to_OA_UID", referencedColumnName = "id")
    @Comment("转OA人")
    private PartyRole toOAUid;

    @Column(name = "to_OA_date")
    @Comment("转OA日期")
    private Date toOADate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "activation_people_id", referencedColumnName = "id")
    @Comment("激活人")
    private PartyRole activationPeopleId;

    @Column(name = "activation_date")
    @Comment("激活日期")
    private Date activationDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "delay_people_id", referencedColumnName = "id")
    @Comment("延期人")
    private PartyRole delayPeopleId;

    @Column(name = "delay_date")
    @Comment("延期日期")
    private Date delayDate;

    @Column(name = "origin", length = 30)
    @Comment("源单据")
    private String origin;

    @Column(name = "origin_business_type", length = 32)
    @Comment("源单据类型")
    private String originBusinessType;

    @Column(name = "origin_type_name")
    @Comment("源单据类型名称")
    private String originTypeName;

    @Column(name = "source", length = 32)
    @Comment("上游单据号码")
    private String source;

    @Column(name = "source_type", length = 64)
    @Comment("上游单据类型")
    private String sourceType;

    @Column(name = "source_type_name")
    @Comment("上游单据名称")
    private String sourceTypeName;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "delete_persion_id", referencedColumnName = "id")
    @Comment("删除人")
    private PartyRole deletePersonId;

    @Column(name = "delete_date")
    @Comment("删除日期")
    private Date deleteDate;

    @Column(name = "site_id")
    @Comment("站点编码")
    private String siteId;

    @Column(name = "site_name")
    @Comment("站点名称")
    private String siteName;

    @Column(name = "purchasing_group")
    @Comment("采购组")
    private String purchasingGroup;

    @Column(name = "adress")
    @Comment("收货地址")
    private String adress;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "supplierShipItem_id", referencedColumnName = "id")
    @Comment("供应商信息")
    private SupplierShipItem supplierShipItem;

    @Column(name = "contact", length = 256)
    @Comment("供应商联系人")
    private String contact;

    @Column(name = "phone", length = 256)
    @Comment("供应商电话")
    private String phone;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "create_uid", referencedColumnName = "id")
    @Comment("创建人")
    private PartyRole createUid;

    @Column(name = "car_license", length = 64)
    @Comment("车牌号码")
    private String carLicense;

    @Column(name = "customer_expand_id")
    @Comment("会员扩展表")
    private String customerExpandId;

    @Column(name = "external_document", length = 256)
    @Comment("外部订单号")
    private String externalDocument;

    @OneToMany(mappedBy = "purchaseOrder", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<PurchaseOrderItem> purchaseItems = new ArrayList<>(); //订单行

    public List<PurchaseOrderItem> getPurchaseItems() {
        for (PurchaseOrderItem item : purchaseItems) {
            item.setPurchaseOrder(this);
            if ("sent".equals(this.state)) item.judgePriceUnit();
        }
        return purchaseItems;
    }


    @Transient
    private Map formatCustomerExpandId; // 查询赋能扩展信息 - 提供给界面使用

    public Map getFormatCustomerExpandId() {
        if (StringUtils.isEmpty(customerExpandId)) return formatCustomerExpandId = null;
        String carLicense = SpringManager.getBean(DomainService.class).invoke("fn.fnCustomerExpandService.accordIdFindCarLicense", MapUtil.mapper("id", customerExpandId));
        return formatCustomerExpandId = MapUtil.mapper("id", customerExpandId, "carLicense", carLicense);
    }

    @Transient
    private Date printDate; // 打印时使用

    public Date getPrintDate() {
        return new Date();
    }

    public void computeAmt() {
        for (PurchaseOrderItem item : purchaseItems) {
            item.computeAmt();
            amtWithoutTax += item.getPriceSubtotal();
            amtTax += item.getPriceTax();
        }
        amtTotal = amtWithoutTax + amtTax;
    }


    @Transient
    private int printCount;

    public int getPrintCount() {
        double count = SpringManager.getBean(DomainService.class).invoke("print.record.findOne", MapUtil.mapper("id", this.getId()));
        return (int) count;
    }

    // 设置开票状态 - 待启用
    public void setInvoiceStatus() {
        if (!state.equals("confirmed") && !state.equals("done")) {
            this.invoiceStatus = "no";
            return;
        }
        for (PurchaseOrderItem item : purchaseItems) {
            int i = Double.compare(item.getQtyInvoiced(), item.computeProductQty());
            if (i == -1) {
                this.invoiceStatus = "to_invoice";
                return;
            } else if (i >= 0) {
                this.invoiceStatus = "invoiced";
            }
        }
    }



    // 设置单据状态
    public void setShipped() {
        boolean receiveQtyGTZeroFlag = false; // 收货数量大于 0
        boolean remainingQtyFlag = false; // 存在剩余数量
        for (PurchaseOrderItem orderItem : getPurchaseItems()) {
            if ("aut".equals(orderItem.getProduct().getType())) continue;
            if (!receiveQtyGTZeroFlag) receiveQtyGTZeroFlag = orderItem.getQtyReceived() > 0;
            if (orderItem.getProductUomQty() - orderItem.getQtyReceived() - orderItem.getStopQty() > 0) {
                remainingQtyFlag = true;
            }
        }
        if (receiveQtyGTZeroFlag && !remainingQtyFlag) {
            setShipped(true);
            setState("done");
        } else if (!receiveQtyGTZeroFlag && !remainingQtyFlag) {
            setState("cancel");
        }

    }

    // 仓储公司判断获取合作方式
    public void judgeComapnyGetCooperation(){
        if (this.location.getCompany().getParty().isWarehousingCompany()) {
            this.setCooperation(SpringManager.getBean(CooperationRepository.class).findOne("consignment"));
        }
    }

    public PurchaseOrder clone() {
        PurchaseOrder order = null;
        ByteArrayOutputStream boutput = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(boutput);
            oos.writeObject(this);
            ByteArrayInputStream bis = new ByteArrayInputStream(boutput.toByteArray());
            ObjectInputStream ios = new ObjectInputStream(bis);
            order = (PurchaseOrder) ios.readObject();

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return order;
    }
}
